<template>
  <div class="p-2">
    <transition :enter-active-class="proxy?.animate.searchAnimate.enter" :leave-active-class="proxy?.animate.searchAnimate.leave">
      <div v-show="showSearch" class="mb-[10px]">
        <el-card shadow="hover">
          <el-form ref="queryFormRef" :model="queryParams" :inline="true">
            <el-form-item label="供应商" prop="providerId">
              <el-select v-model="queryParams.providerId" placeholder="请选择供应商" clearable @keyup.enter="handleQuery">
                <el-option v-for="item in allProviders" :key="item.id" :label="item.name" :value="item.id" />
              </el-select>
            </el-form-item>
            <el-form-item label="通道名称" prop="channelName">
              <el-input v-model="queryParams.channelName" placeholder="请输入通道名称" clearable @keyup.enter="handleQuery" />
            </el-form-item>
            <el-form-item label="归属省" prop="provinceCode">
              <el-select v-model="queryParams.provinceCode" placeholder="请选择归属省" clearable filterable>
                <el-option
                  v-for="province in provinces"
                  :key="province.code"
                  :label="province.name"
                  :value="province.code"
                />
              </el-select>
            </el-form-item>
            <el-form-item label="运营商" prop="ispCode">
              <el-select v-model="queryParams.ispCode" placeholder="请选择运营商" clearable>
                <el-option
                  :key="0"
                  :label="'全国'"
                  :value="0"
                />
                <el-option
                  v-for="item in ispOptions"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                />
              </el-select>
            </el-form-item>
            <el-form-item>
              <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
              <el-button icon="Refresh" @click="resetQuery">重置</el-button>
            </el-form-item>
          </el-form>
        </el-card>
      </div>
    </transition>

    <el-card shadow="never">
      <template #header>
        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button type="primary" plain icon="Plus" @click="handleAdd" v-hasPermi="['provider:providerChannel:add']">新增</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="success" plain icon="Edit" :disabled="single" @click="handleUpdate()" v-hasPermi="['provider:providerChannel:edit']">修改</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="danger" plain icon="Delete" :disabled="multiple" @click="handleDelete()" v-hasPermi="['provider:providerChannel:remove']">删除</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="warning" plain icon="Download" @click="handleExport" v-hasPermi="['provider:providerChannel:export']">导出</el-button>
          </el-col>
          <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
        </el-row>
      </template>

      <el-table v-loading="loading" :data="providerChannelList" @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column label="通道id" align="center" prop="id" v-if="true" />
        <el-table-column label="供应商id" align="center" prop="providerId" />
        <el-table-column label="通道名称" align="center" prop="channelName" />
        <el-table-column label="归属省" align="center" prop="provinceCode" >
          <template #default="scope">
            {{provinceMap.get(scope.row.provinceCode)}}
          </template>
        </el-table-column>

        <el-table-column label="通道说明" align="center" prop="remark" />
        <el-table-column label="运营商" align="center" prop="ispCode" />
        <el-table-column label="单价" align="center" prop="price" />
        <el-table-column label="状态" align="center" prop="status" />
        <el-table-column label="敏感词" align="center" prop="sensitiveWord" />
        <el-table-column label="屏蔽省" align="center" prop="hideProvinceName"  >
          <template #default="scope">
            <!--显示provinceMap中省级单位名称-->
<!--            {{(scope.row.hideProvinceName?.split(','))}}-->
            {{(scope.row.hideProvinceName?.split(',')).map(item => provinceMap.get(item)).join(',')}}
          </template>
        </el-table-column>
        <el-table-column label="扩展码长度限制" align="center" prop="extCodeLenLimit" />
        <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
          <template #default="scope">
            <el-tooltip content="修改" placement="top">
              <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)" v-hasPermi="['provider:providerChannel:edit']"></el-button>
            </el-tooltip>
            <el-tooltip content="删除" placement="top">
              <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)" v-hasPermi="['provider:providerChannel:remove']"></el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>

      <pagination v-show="total > 0" :total="total" v-model:page="queryParams.pageNum" v-model:limit="queryParams.pageSize" @pagination="getList" />
    </el-card>
    <!-- 添加或修改供应商通道对话框 -->
    <el-dialog :title="dialog.title" v-model="dialog.visible" width="40%" append-to-body>
      <el-form ref="providerChannelFormRef" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="供应商" prop="providerId">
          <el-select v-model="form.providerId" placeholder="请选择供应商">
            <el-option
              v-for="item in allProviders"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="通道名称" prop="channelName">
          <el-input v-model="form.channelName" placeholder="请输入通道名称" readonly/>
        </el-form-item>
        <el-form-item label="归属省" prop="provinceCode">
          <el-select v-model="form.provinceCode" placeholder="请选择归属省" clearable filterable>
            <el-option
              :key="0"
              :label="'全国'"
              :value="'0'"
            />
            <el-option
              v-for="province in provinces"
              :key="province.code"
              :label="province.name"
              :value="province.code"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="屏蔽省" prop="hideProvinceName">
          <el-select
            v-model="form.hideProvinceName"
            placeholder="请选择屏蔽省"
            multiple
            clearable
            filterable
          >
            <el-option
              v-for="province in provinces"
              :key="province.code"
              :label="province.name"
              :value="province.code"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="通道说明" prop="remark">
            <el-input v-model="form.remark" type="textarea" placeholder="请输入内容" />
        </el-form-item>
        <el-form-item label="运营商" prop="ispCode">
          <el-select v-model="form.ispCode" placeholder="请选择运营商" clearable>
            <el-option
              v-for="item in ispOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="单价" prop="price">
          <el-input v-model="form.price" placeholder="请输入单价" />
        </el-form-item>
        <el-form-item label="敏感词" prop="sensitiveWord">
            <el-input v-model="form.sensitiveWord" type="textarea" placeholder="请输入内容" />
        </el-form-item>

        <el-form-item label="扩展码长度限制" prop="extCodeLenLimit">
            <el-input-number v-model="form.extCodeLenLimit" :min="-1"   />
            <el-text :style="{'margin-left':'10px','color':'red'}">-1、不限制长度; 0、不支持拓展; >0、限制位数</el-text>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button :loading="buttonLoading" type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="ProviderChannel" lang="ts">
import {
  addProviderChannel,
  delProviderChannel,
  getProviderChannel,
  listProviderChannel,
  updateProviderChannel
} from '@/api/provider/providerChannel';
import {ProviderChannelForm, ProviderChannelQuery, ProviderChannelVO} from '@/api/provider/providerChannel/types';
import {listAllProvider} from "@/api/provider/provider";
import {ProviderVO} from "@/api/provider/provider/types";

const { proxy } = getCurrentInstance() as ComponentInternalInstance;

const providerChannelList = ref<ProviderChannelVO[]>([]);
const buttonLoading = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref<Array<string | number>>([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);

const queryFormRef = ref<ElFormInstance>();
const providerChannelFormRef = ref<ElFormInstance>();

const dialog = reactive<DialogOption>({
  visible: false,
  title: ''
});

const ispOptions = ref([
  { label: '全网', value: 'ALL' },
  { label: '移动', value: 'CMCC' },
  { label: '联通', value: 'CUCC' },
  { label: '电信', value: 'CTCC' }
]);

// 在script setup部分添加
const provinces = ref([
  {code: '11', name: '北京市'},
  {code: '12', name: '天津市'},
  {code: '13', name: '河北省'},
  {code: '14', name: '山西省'},
  {code: '15', name: '内蒙古自治区'},
  {code: '21', name: '辽宁省'},
  {code: '22', name: '吉林省'},
  {code: '23', name: '黑龙江省'},
  {code: '31', name: '上海市'},
  {code: '32', name: '江苏省'},
  {code: '33', name: '浙江省'},
  {code: '34', name: '安徽省'},
  {code: '35', name: '福建省'},
  {code: '36', name: '江西省'},
  {code: '37', name: '山东省'},
  {code: '41', name: '河南省'},
  {code: '42', name: '湖北省'},
  {code: '43', name: '湖南省'},
  {code: '44', name: '广东省'},
  {code: '45', name: '广西壮族自治区'},
  {code: '46', name: '海南省'},
  {code: '50', name: '重庆市'},
  {code: '51', name: '四川省'},
  {code: '52', name: '贵州省'},
  {code: '53', name: '云南省'},
  {code: '54', name: '西藏自治区'},
  {code: '61', name: '陕西省'},
  {code: '62', name: '甘肃省'},
  {code: '63', name: '青海省'},
  {code: '64', name: '宁夏回族自治区'},
  {code: '65', name: '新疆维吾尔自治区'},
  {code: '71', name: '台湾省'},
  {code: '81', name: '香港特别行政区'},
  {code: '82', name: '澳门特别行政区'}
]);
// 将pronvinces数组转换为Map,同时添加全国0=>全国,转换为响应式对象
const provinceMap = reactive(new Map(provinces.value.map(province => [province.code, province.name])));
provinceMap.set('0', '全国');

const initFormData: ProviderChannelForm = {
  id: undefined,
  providerId: undefined,
  channelName: undefined,
  provinceCode: undefined,
  remark: undefined,
  ispCode: undefined,
  price: undefined,
  status: 1,
  sensitiveWord: undefined,
  hideProvinceName: undefined,
  extCodeLenLimit: -1,
}
const data = reactive<PageData<ProviderChannelForm, ProviderChannelQuery>>({
  form: {...initFormData},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    providerId: undefined,
    channelName: undefined,
    provinceCode: undefined,
    ispCode: undefined,
    price: undefined,
    status: undefined,
    sensitiveWord: undefined,
    hideProvinceName: undefined,
    extCodeLenLimit: undefined,
    params: {
    }
  },
  rules: {
    providerId: [
      { required: true, message: "供应商不能为空", trigger: "blur" },
    ],
    channelName: [
      { required: true, message: "通道名称不能为空", trigger: "blur" },
    ],
    provinceCode: [
      { required: true, message: "省份不能为空", trigger: "blur" },
    ],
    ispCode: [
      { required: true, message: "运营商不能为空", trigger: "blur" },
    ],
    price: [
      { required: true, message: "价格不能为空", trigger: "blur" },
    ],
  }
});

const { queryParams, form, rules } = toRefs(data);

/** 查询供应商通道列表 */
const getList = async () => {
  loading.value = true;
  const res = await listProviderChannel(queryParams.value);
  providerChannelList.value = res.rows;
  total.value = res.total;
  loading.value = false;
}

/** 取消按钮 */
const cancel = () => {
  reset();
  dialog.visible = false;
}

/** 表单重置 */
const reset = () => {
  form.value = {...initFormData};
  providerChannelFormRef.value?.resetFields();
}

/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.value.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
const resetQuery = () => {
  queryFormRef.value?.resetFields();
  handleQuery();
}

/** 多选框选中数据 */
const handleSelectionChange = (selection: ProviderChannelVO[]) => {
  ids.value = selection.map(item => item.id);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}

/** 新增按钮操作 */
const handleAdd = () => {
  reset();
  dialog.visible = true;
  dialog.title = "添加供应商通道";
}

/** 修改按钮操作 */
const handleUpdate = async (row?: ProviderChannelVO) => {
  reset();
  const _id = row?.id || ids.value[0]
  const res = await getProviderChannel(_id);
  Object.assign(form.value, res.data);
  form.value.hideProvinceName = res.data.hideProvinceName?.split(',');
  dialog.visible = true;
  dialog.title = "修改供应商通道";
}

/** 提交按钮 */
const submitForm = () => {
  providerChannelFormRef.value?.validate(async (valid: boolean) => {
    if (valid) {
      buttonLoading.value = true;
      const submitData = {...form.value};
      submitData.hideProvinceName = form.value.hideProvinceName?.join(',');
      console.log("submitForm",submitData);
      if (form.value.id) {
        await updateProviderChannel(submitData).finally(() =>  buttonLoading.value = false);
      } else {
        await addProviderChannel(submitData).finally(() =>  buttonLoading.value = false);
      }
      proxy?.$modal.msgSuccess("操作成功");
      dialog.visible = false;
      await getList();
    }
  });
}

/** 删除按钮操作 */
const handleDelete = async (row?: ProviderChannelVO) => {
  const _ids = row?.id || ids.value;
  await proxy?.$modal.confirm('是否确认删除供应商通道编号为"' + _ids + '"的数据项？').finally(() => loading.value = false);
  await delProviderChannel(_ids);
  proxy?.$modal.msgSuccess("删除成功");
  await getList();
}

/** 导出按钮操作 */
const handleExport = () => {
  proxy?.download('provider/providerChannel/export', {
    ...queryParams.value
  }, `providerChannel_${new Date().getTime()}.xlsx`)
}
const allProviders =  ref<ProviderVO[]>([]);
/**
 * 获取所有供应商
 */
const getAllProviders = async () => {
  allProviders.value = await listAllProvider();
  console.log("allProviders",allProviders.value)
}

// 在script setup部分添加
const generateChannelName = () => {
  const provider = allProviders.value.find(p => p.id === form.value.providerId);
  let province = provinces.value.find(p => p.code === form.value.provinceCode);
  if(!province){
    province = {code:'0',name:'全国'}
  }
  const ispOption = ispOptions.value.find(p => p.value === form.value.ispCode);
  console.log("generateChannelName",provider?.name,province?.name,form.value.price,ispOption?.label)
  if (provider?.name && province?.name && form.value.price&& ispOption?.label ){
    return `【${provider?.name }】 ${province?.name }${ispOption?.label }${form.value.price }元`;
  }else{
    return "";
  }

};

// 监听相关字段变化
watch([() => form.value.providerId, () => form.value.provinceCode,()=>form.value.ispCode, () => form.value.price], () => {
  form.value.channelName = generateChannelName();
});

onMounted(() => {
  getList();
  getAllProviders();
});
</script>
